import { useState } from 'react';
import { Button, Divider, Input } from 'antd';
import { useLatest } from 'ahooks';

// react-virtualized-scroll
// https://github.com/clauderic/react-tiny-virtual-list
import VirtualList from 'react-tiny-virtual-list';
// antd-table 通过 react-window 引入虚拟滚动方案，实现 100000 条数据的高性能表格。
// antd-tree 使用 height 属性则切换为虚拟滚动。
// rc-virtual-list
// https://juejin.cn/post/7023742941621387301
// https://github.com/react-component/virtual-list/blob/master/src/List.tsx

export default function List() {
  return (
    <div>
      <p>大数据渲染</p>
      <Divider />
      <Demo1 />
      <Divider />
      <Demo2 />
      <Divider />
      <Demo3 />
    </div>
  );
}

function Demo1() {
  const [list, setList] = useState<number[]>([]);
  const handleClick = () => {
    let starTime = new Date().getTime();
    // long task
    setList(new Array(30000).fill(0));
    setTimeout(() => {
      const end = new Date().getTime();
      console.log('花费的时间', (end - starTime) / 1000 + '秒');
    }, 0);
  };
  return (
    <ul>
      {/* 渲染的时候这个input不能交互 */}
      <Input />
      <Button type="primary" onClick={handleClick}>
        点击
      </Button>
      {list.map((item: number, index: number) => (
        <li key={index}>{index}</li>
      ))}
    </ul>
  );
}

// 时间分片
function Demo2() {
  const [list, setList] = useState<number[]>([]);
  const latestListRef = useLatest(list);
  const handleClick = () => {
    timeSlice(30000);
  };

  const timeSlice = (times: number) => {
    // setTimeout不是很流畅
    // requestAnimationFrame() 每帧都会执行一次
    // requestIdleCallback 在浏览器空闲的时候执行
    // react内部使用的是 MessageChannel concurrent并发的渲染
    requestIdleCallback(() => {
      let minus = times >= 100 ? 100 : times;
      times -= minus;
      // 将任务分为很多的小片
      // console.log(minus, list);
      // list获取到的是旧的值 使用ref来获取最新的值
      // setList([...list, ...new Array(minus).fill(0)]);
      setList([...latestListRef?.current, ...new Array(minus).fill(0)]);
      if (times > 0) {
        // 如果还有就需要执行这个任务
        console.log(times, 'times');
        timeSlice(times);
      }
    });
  };

  return (
    <ul>
      {/* 渲染的时候这个input不能交互 */}
      <Input />
      <Button type="primary" onClick={handleClick}>
        点击
      </Button>
      {list.map((item: number, index: number) => (
        <li key={index}>{index}</li>
      ))}
    </ul>
  );
}

const data = new Array(300).fill(0);

function Demo3() {
  return (
    <VirtualList
      width="50%"
      height={500}
      itemCount={data.length}
      itemSize={50}
      renderItem={(data) => {
        let { index, style } = data;
        console.log(data);
        return (
          <div
            key={index}
            style={{ ...style, backgroundColor: index % 2 === 0 ? 'green' : 'orange' }}
          >
            {index + 1}
          </div>
        );
      }}
    />
  );
}
